package site.oldpei.manage.nomal.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.XmlUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import site.oldpei.manage.erupt.entity.ActorInfo;
import site.oldpei.manage.erupt.entity.VedioGenre;
import site.oldpei.manage.erupt.entity.VedioInfo;
import site.oldpei.manage.erupt.entity.VedioTag;
import site.oldpei.manage.nomal.mapper.ActorInfoMapper;
import site.oldpei.manage.nomal.mapper.VedioGenreMapper;
import site.oldpei.manage.nomal.mapper.VedioInfoMapper;
import site.oldpei.manage.nomal.mapper.VedioTagMapper;
import site.oldpei.manage.nomal.service.BatchService;
import site.oldpei.manage.nomal.utils.XMLUtils;
import xyz.erupt.jpa.dao.EruptDao;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Service
public class BatchServiceImpl implements BatchService {
    private final Logger log = LoggerFactory.getLogger(BatchServiceImpl.class);
    @Autowired
    private ActorInfoMapper actorInfoMapper;
    @Autowired
    private VedioGenreMapper vedioGenreMapper;
    @Autowired
    private VedioInfoMapper vedioInfoMapper;
    @Autowired
    private VedioTagMapper vedioTagMapper;

    @Value("${local.fileSuffix}")
    private String allownSuffixs;
    @Value("${erupt.upload-path}")
    private String uploadPath;
    private List<String> allownSuffixList;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scan(String path) {
        log.info("扫描:{}", path);
        File filePath = new File(path);
        if (!FileUtil.isDirectory(filePath)) {
            return;
        }
        List<File> files = FileUtil.loopFiles(filePath);
        files.stream().filter(file -> FileUtil.pathEndsWith(file, "nfo")).forEach(this::saveFileToDB);
    }
    @Resource
    private EruptDao eruptDao;
    @SneakyThrows
    private void saveFileToDB(File file) {
        if (allownSuffixList == null) {
            allownSuffixList = CollectionUtil.newArrayList(allownSuffixs.split(";"));
        }
        String path = file.getParent();
        File[] ls = FileUtil.ls(path);
        Document document = XmlUtil.readXML(file);
        String title = XMLUtils.getValueByName(document, "title");
        log.info("title:{}", title);
        String identificationCode = title.substring(0, title.indexOf(" "));
        log.info("identificationCode:{}", identificationCode);
        List<String> genreStrs = XMLUtils.getValueListByName(document, "genre");
        List<VedioGenre> genres = new ArrayList<>();
        for (String genreStr : genreStrs) {
            genres.add(VedioGenre.builder().genre(genreStr).build());
        }
        List<String> tagStrs = XMLUtils.getValueListByName(document, "tag");
        List<VedioTag> tags = new ArrayList<>();
        for (String tagStr : tagStrs) {
            tags.add(VedioTag.builder().tag(tagStr).build());
        }
        List<String> names = XMLUtils.getValueListByName(document, "name");
        List<ActorInfo> actors = new ArrayList<>();
        for (String actorName : names) {
            actors.add(ActorInfo.builder().name(actorName).build());
        }
        VedioInfo build = VedioInfo.builder()
                .identificationCode(identificationCode)
                .title(title)
                .rating(XMLUtils.getValueByName(document, "rating"))
                .plot(XMLUtils.getValueByName(document, "plot"))
                .runtime(XMLUtils.getValueByName(document, "runtime"))
                .genres(genres)
                .tags(tags)
                .country(XMLUtils.getValueByName(document, "country"))
                .director(XMLUtils.getValueByName(document, "director"))
                .premiered(XMLUtils.getValueByName(document, "premiered"))
                .studio(XMLUtils.getValueByName(document, "studio"))
                .actors(actors)
                .isAuto(true)
                .build();

        for (File vedio : ls) {
            if (allownSuffixList.contains(FileUtil.getSuffix(vedio))) {
                build.setFilePath(vedio.getAbsolutePath().replace(uploadPath, ""));//视频文件路径
            }
            if (StringUtils.contains(vedio.getName(), "fanart")) {
                build.setFanart(vedio.getAbsolutePath().replace(uploadPath, ""));
            }
            if (StringUtils.contains(vedio.getName(), "poster")) {
                build.setPoster(vedio.getAbsolutePath().replace(uploadPath, ""));
            }
        }
        if (StringUtils.isEmpty(build.getFilePath())) {
            return;
        }
        eruptDao.persist(build);
        // 使用 flush 方法可以在线程结束前入库，如果批处理数据建议每千次（新增、更新、删除）调用一次 flush
        eruptDao.flush();
    }

    public static void main(String[] args) throws Exception {
        Document document = XmlUtil.readXML("F:\\develop\\ws\\jellyfin\\media\\av\\未剪辑\\有码\\AIKA\\[SDDE-450]\\SDDE-450.nfo");
        NodeList actors = document.getElementsByTagName("name");
        for (int i = 0; i < actors.getLength(); i++) {
            Node item = actors.item(i);
            Node name = item.getAttributes().getNamedItem("name");
            String textContent = name.getTextContent();
            System.out.println(textContent);

        }
//
//        List<ActorInfo> actor = XMLUtils.getValueListByName(document, "/movie/actor/name", ActorInfo.class);
//        for (ActorInfo actorInfo : actor) {
//            System.out.println(actorInfo);
//        }

    }


}
